package cn.smp.server.handler;

import cn.smp.message.GroupCreateRequestMessage;
import cn.smp.message.GroupCreateResponseMessage;
import cn.smp.server.session.Group;
import cn.smp.server.session.GroupSession;
import cn.smp.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        final String groupName = msg.getGroupName();
        final Set<String> members = msg.getMembers();
        //群管理器
        final GroupSession groupSession = GroupSessionFactory.getGroupSession();
        final Group group = groupSession.createGroup(groupName, members);
        //建群失败，直接返回
        if (group != null) {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,groupName+" 已经存在。"));
            return;
        }

        //发送成功消息
        ctx.writeAndFlush(new GroupCreateResponseMessage(true,groupName+" 创建成功。"));

        //发送拉群消息
        final List<Channel> channels = groupSession.getMembersChannel(groupName);
        for (Channel channel : channels) {
            channel.writeAndFlush(new GroupCreateResponseMessage(true,"您已被拉入 "+groupName));
        }
    }
}
